﻿/*-------------------------------------------------------------------------
 * 命名空间名称/文件名: NoticeApp/Project
 * 功能: N/A
 * 说明: 
 * 创建时间: 2023/9/11 16:43:48
 * 创建人: 28733
 * 邮箱: 2873349982@qq.com
 * 修改人:    
 * 修改时间:    
 * 修改说明:  
 *-------------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace NoticeApp
{
    public class Project
    {
        public string? Code { get; set; }
        public string? Name { get; set; }
    }

    // 订阅者
    public interface ISubscriber
    {
        public void OnCreateProj(Project project);
    }

    public class Subscriber_A : ISubscriber
    {
        public string? ClientCode { get; set; }
        public string? Name { get; set; }
        public void OnCreateProj(Project project)
        {
            Console.WriteLine($"{this.Name}接收到了项目{project.Code}-{project.Name}");
        }
    }

    public class Subscriber_B : ISubscriber
    {
        public string? AppCode { get; set; }
        public string? AppName { get; set; }
        public void OnCreateProj(Project project)
        {
            Console.WriteLine($"应用程序{this.AppName}接收到了项目{project.Code}-{project.Name}");
        }
    }

    // 发布者
    class Publisher
    {
        private List<ISubscriber> subscribers { get; set; } = new List<ISubscriber>();

        private delegate void CreateProjectDelegate(Project project);
        private event CreateProjectDelegate CreateProj;
        public void CreateProject(string code, string name)
        {
            Project project = new Project
            {
                Code = code,
                Name = name,
            };
            
            CreateProj(project);
        }
        public void GetSubscribers()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("./app.config");

            XmlNodeList nodes = doc.SelectNodes("/configuration/Subscribers/Subscriber");
            foreach (XmlNode node in nodes)
            {
                string className = node.ChildNodes[0].InnerText;
                // 获取类型
                Type type = Type.GetType(className);

                // 创建对象
                ISubscriber obj = (ISubscriber)Activator.CreateInstance(type);

                for (int i = 1; i < node.ChildNodes.Count; i++)
                {
                    // 获取节点的名称和值
                    string name = node.ChildNodes[i].Name;
                    string value = node.ChildNodes[i].InnerText;
                    type.GetProperty(name).SetValue(obj, value);
                }
                this.CreateProj += obj.OnCreateProj;
                this.subscribers.Add(obj);
            }
        }
    }
}
